﻿using System;
using System.Linq;
using System.Windows.Controls;

namespace DynamicGeometry
{
    public class EnumPropertyEditorFactory : BasePropertyEditorFactory<EnumPropertyEditor>
    {
        public override bool SupportsProperty(System.Reflection.PropertyInfo property)
        {
            return property.PropertyType.IsEnum
                && base.SupportsProperty(property);
        }
    }

    public class EnumPropertyEditor : ComboboxPropertyEditor, IPropertyEditor
    {
        public override void Init()
        {
            guard = true;
            var propertyType = Property.PropertyType;
            Items = from f in propertyType.GetFields()
                    where f.FieldType == propertyType
                    select Enum.Parse(propertyType, f.Name, true).ToString();
            //base.Init();
            ComboBox.ItemsSource = Items;
            UpdateSelectedItem();
            guard = false;
        }

        protected override void SetValue(object value)
        {
            base.SetValue(Enum.Parse(Property.PropertyType, value.ToString(), false));
        }

        public override void UpdateSelectedItem()
        {
            var value = Property.GetValue(Target, null);
            foreach (var item in Items)
            {
                if (item.Equals(value.ToString()))
                {
                    ComboBox.SelectedItem = item;
                }
            }
        }
    }
}
